package sunwul.mall.commoncore.interceptor;

import cn.hutool.core.util.ObjectUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sunwul.mall.commonbase.constant.AuthConstants;

import javax.servlet.http.HttpServletRequest;

/**
 * @author sunwul
 * @date 2024/12/30 11:30
 * @description feign拦截器, 解决服务之间调用没有token的情况
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 当前请求上下文
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ObjectUtil.isNotNull(requestAttributes)) {
            // 请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            if (ObjectUtil.isNotNull(request)) {
                //获取当前请求头中的token值, 传递到下一个请求的请求头中
                String authorization = request.getHeader(AuthConstants.AUTHORIZATION);
                requestTemplate.header(AuthConstants.AUTHORIZATION, authorization);
                return;
            }
        }
        // TODO 非浏览器过来的请求,携带的token(内部token, 不失效)
        requestTemplate.header(AuthConstants.AUTHORIZATION, AuthConstants.BEARER + "f3ce6558-a087-4259-b636-23e44e00829d");
    }
}
